package com.xunua.myaudioandvideolearning.camera1

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.lang.Exception

/**
 * @author: linxunyou
 * @description:
 * @date :2022/5/7 11:39
 **/
class LocalSurfaceView  @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes), Camera.PreviewCallback,
    SurfaceHolder.Callback {
    private val h264Encoder:H264CameraEncoder by lazy {
        H264CameraEncoder(mPreviewSize.width,mPreviewSize.height).apply {
            startLive()
        }
    }
    private lateinit var mPreviewSize: Camera.Size
    //预览宽高，就能得到yuv多大
    private lateinit var buffer:ByteArray
    //将camera显示到surfaceView
    private val mCamera:Camera by lazy { Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK).apply {
        var parameters = parameters
        mPreviewSize = parameters.previewSize
        try {
            setPreviewDisplay(holder)
            //设置横着
            setDisplayOrientation(90)
            buffer= ByteArray(mPreviewSize.height*mPreviewSize.width*3/2)//NV21
            addCallbackBuffer(buffer)
            setPreviewCallbackWithBuffer(this@LocalSurfaceView)
            startPreview()
        }catch (e:Exception){

        }
    } }

    init {
        holder.addCallback(this@LocalSurfaceView)
    }

    private fun startPreview(){
        mCamera
    }

    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        if (data==null) return
        //bytes yuv 摄像头得到的拍摄数据是横着的
        //编码 时需要对视频原数据进行 宽高 交换
        //数据
        h264Encoder.encodeFrame(data)
        mCamera.addCallbackBuffer(data)
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

    }
}